import org.junit.Test;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

/**
 * 在给定的目标数组中找出任意两值之和为目标数值的两个整数
 */
public class Solution {

    @Test
    public void clibe() {
        int[] a = {1, 3, 4, 5};
        long startTime1 =  System.currentTimeMillis();
        int[] ints = Sum1(a, 8);
        long endTime1 =  System.currentTimeMillis();
        System.out.println("sum1="+Arrays.toString(ints)+",使用时间:"+ (endTime1-startTime1));

        long startTime2 =  System.currentTimeMillis();
        int[] sum2 = Sum2(a,8);
        long endTime2 =  System.currentTimeMillis();
        System.out.println("sum2="+Arrays.toString(sum2)+",使用时间:"+ (endTime2-startTime2));
    }

    /**
     * 方法一：暴力组合
     */
    public int[] Sum1(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                if (nums[i] + nums[j] == target) {
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }

    public int[] Sum2(int[] nums,int target){
        Map<Integer,Integer> storeNums = new HashMap<Integer, Integer>(nums.length,1);
        int[] result = new int[2];
        for (int i = 0; i < nums.length; i++) {
            int another = target-nums[i];
            Integer anotherIndex = storeNums.get(another);
            if (null != anotherIndex) {
                result[0] = anotherIndex;
                result[1] = i;
                break;
            }else {
                storeNums.put(nums[i],i);
            }
        }
        return result;
    }
}
